import { message } from 'antd'
import api from 'api'
import { pathMatchRegexp } from 'utils'
import moment from 'moment'
import store from 'store'

const {
  changeNote,
  // projects,
  deviceonfo,
  devicerename,
  changeCharge,
  changeProject,
  changeFirmwareVersion,
  changeLastServingTime,
  devicehistory,
  gethistorydata,
  getresolvedhistorydata,
  getrealtimedata,
  subUpload,
  unsubUpload,
  deviceregeo,
  getUploadDatasList,
  getRelations,
  getAllDeviceGeo,
} = api
const emptystate = {
  EditingGeo: false,
  data: {},
  deviceid: '',
  pathquery: {},
  historys: undefined,
  laterdata: undefined, //{ v: [], e: [], p: [] }
  rslaterdata: undefined,
  realtime: undefined,
  dataform: undefined,
  relations: undefined,

  onReceiveReport: undefined,
  SubReport: false,
  AllChildGeo: [],
}
const modelEdit = () => {}
export default {
  namespace: 'userDetail',

  state: {
    ...emptystate,

    hisstartdate: '',
    hisenddate: '',

    resstartdate: '',
    resenddate: '',

    dtfstartdate: '',
    dtfenddate: '',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        let { pathname } = location
        const match = pathMatchRegexp('/devices/:id', pathname)
        if (match) {
          dispatch({ type: 'query', payload: { deviceid: match[1] } })
          dispatch({
            type: 'devicehistory',
          })
          // dispatch({ type: 'querySuccess', payload: { deviceid: match[1] } });
        }
        dispatch({
          type: 'querySuccess',
          payload: { pathquery: location.query },
        })
      })
    },
  },

  effects: {
    // *onchangepath({ payload }, { call, put }) {
    //   const { deviceid } = yield select(_ => _.userDetail);
    //   if (payload.deviceid !== deviceid) {
    //   }
    // },
    *clearstore({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          ...emptystate,
        },
      })
    },
    *query({ payload }, { call, put }) {
      if (payload.deviceid) {
        const data = yield call(deviceonfo, payload)
        // const { success, message, status, ...other } = data.result
        // console.log(JSON.stringify(data));
        yield put({
          type: 'querySuccess',
          payload: {
            data: data.result,
            ...(payload.deviceid ? { deviceid: payload.deviceid } : {}),
          },
        })
      }
    },

    *rename({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      yield call(devicerename, payload)
      message.destroy()
      message.success('修改成功')
    },
    *changeIMEI({ payload }, { call, put }) {
      // const data = yield call(devicerename, payload)
      message.error('"IMEI"是“只读”属性，不可修改！')
    },
    *changeRegisterTime({ payload }, { call, put }) {
      // const data = yield call(devicerename, payload)
      message.error('"注册时间"是“只读”属性，不可修改！')
    },
    *changeCharge({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      yield call(changeCharge, payload)
      message.destroy()
      message.success('修改成功')
    },
    *changeLocation({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      yield call(deviceregeo, payload)
      message.destroy()
      message.success('修改成功')
      // message.error('"所在区域"是“只读”属性，不可修改！')
    },
    *changeProject({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      const { result } = yield call(changeProject, payload)
      if (result.successed >= 1) {
        message.destroy()
        message.success('修改成功')
      } else {
        message.error('修改失败！')
      }
    },
    *changeFirmwareVersion({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      yield call(changeFirmwareVersion, payload)
      message.destroy()
      message.success('修改成功')
    },
    *changeLastServingTime({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      yield call(changeLastServingTime, payload)
      message.destroy()
      message.success('修改成功')
    },
    *changeNote({ payload }, { call, put }) {
      message.loading('修改中...', 0)
      yield call(changeNote, payload)
      message.destroy()
      message.success('修改成功')
    },
    *devicehistory({ payload }, { call, put, select }) {
      const { historys, deviceid } = yield select(_ => _.userDetail)
      if (deviceid) {
        let skip = 0
        if (payload && payload.skip != undefined) {
          skip = payload.skip
        } else {
          skip = historys ? historys.length : 0
        }
        const { result } = yield call(devicehistory, {
          deviceid,
          skip,
        })
        yield put({
          type: 'updateState',
          payload: {
            historys: (skip != 0 ? (historys ? historys : []) : []).concat(
              result
            ),
          },
        })
      }
    },
    *refreshhistory({ payload }, { call, put, select }) {
      // yield put({
      //   type: 'updateState',
      //   payload: { historys: [] },
      // })
      yield put({ type: 'devicehistory', payload: { skip: 0 } })
    },
    *getRelations({ payload }, { call, put, select }) {
      const { result } = yield call(getRelations, payload)
      yield put({
        type: 'updateState',
        payload: {
          relations: result,
        },
      })
    },
    *gethistorydata({ payload }, { call, put, select }) {
      let { hisstartdate, hisenddate } = payload
      let startdate, enddate
      if (!hisstartdate || !hisenddate) {
        enddate = moment().format('YYYY-MM-DD')
        startdate = moment()
          .subtract(1, 'years')
          .format('YYYY-MM-DD')
      } else {
        enddate = hisenddate
        startdate = hisstartdate
      }
      const { result } = yield call(gethistorydata, {
        ...payload,
        startdate,
        enddate,
      })
      let data = { v: [], e: [], p: [], led_v: [], pv_v: [], tp: [] }
      if (startdate != enddate) {
        for (let index in result) {
          try {
            let item = result[index]
            let { Data, TimeToken } = item
            if (!Data) continue
            // let indexdate = moment(TimeToken).format('YYYY-MM-DD') //new Date(item.TimeToken).Format('yyyy-MM-dd');
            let { indexs, strindexs, V, E, P, LED_V, PV_V, TP } = Data
            let nowdate = moment().format('YYYY-MM-DD')
            if (indexs && strindexs)
              for (let i2 in strindexs) {
                let indexdate = strindexs[i2].split(' ')[0] //moment(TimeToken).format('YYYY-MM-DD') //new Date(item.TimeToken).Format('yyyy-MM-dd');
                try {
                  let indextime = moment(
                    nowdate + ' ' + strindexs[i2].split(' ')[1],
                    'YYYY-MM-DD HH:mm:ss:SSS'
                  ).valueOf()
                  let v = V[i2] / 10
                  let e = E[i2] / 10
                  let p = P[i2] / 10
                  let led_v = LED_V[i2] / 10
                  let pv_v = PV_V[i2] / 10
                  let tp = TP[i2] - 100
                  data.v.push([indexdate, indextime, v])
                  data.e.push([indexdate, indextime, e])
                  data.p.push([indexdate, indextime, p])
                  data.led_v.push([indexdate, indextime, led_v])
                  data.pv_v.push([indexdate, indextime, pv_v])
                  data.tp.push([indexdate, indextime, tp])
                } catch {}
              }
          } catch {}
        }
      } else {
        for (let index in result) {
          try {
            let item = result[index]
            let { Data, TimeToken } = item
            if (!Data) continue
            // let indexdate = moment(TimeToken).format('YYYY-MM-DD'); //new Date(item.TimeToken).Format('yyyy-MM-dd');
            let { indexs, strindexs, V, E, P, LED_V, PV_V, TP } = Data
            // let nowdate = moment().format('YYYY-MM-DD');
            if (indexs)
              for (let i2 in indexs) {
                try {
                  let indextime = indexs[i2] //moment(nowdate + " " + strindexs[i2].split(' ')[1], 'YYYY-MM-DD HH:mm:ss:SSS').valueOf();
                  let v = V[i2] / 10
                  let e = E[i2] / 10
                  let p = P[i2] / 10
                  let led_v = LED_V[i2] / 10
                  let pv_v = PV_V[i2] / 10
                  let tp = TP[i2] - 100
                  data.v.push([indextime, v])
                  data.e.push([indextime, e])
                  data.p.push([indextime, p])
                  data.led_v.push([indextime, led_v])
                  data.pv_v.push([indextime, pv_v])
                  data.tp.push([indextime, tp])
                } catch {}
              }
          } catch {}
        }
      }

      yield put({
        type: 'updateState',
        payload: {
          laterdata: data,
          hisstartdate: startdate,
          hisenddate: enddate,
        },
      })
    },
    *getrealtimedata({ payload }, { call, put, select }) {
      const { result } = yield call(getrealtimedata, payload)
      let data = {
        v: [],
        e: [],
        p: [],
        led_v: [],
        pv_v: [],
        tp: [],
        max: 0,
        min: 0,
      }
      try {
        let { indexs, strindexs, V, E, P, LED_V, PV_V, TP } = result
        if (indexs)
          for (let i2 in indexs) {
            try {
              let indextime = indexs[i2]
              let v = V[i2] / 10
              let e = E[i2] / 10
              let p = P[i2] / 10

              let led_v = LED_V[i2] / 10
              let pv_v = PV_V[i2] / 10
              let tp = TP[i2] - 100

              data.v.push([indextime, v])
              data.e.push([indextime, e])
              data.p.push([indextime, p])
              data.led_v.push([indextime, led_v])
              data.pv_v.push([indextime, pv_v])
              data.tp.push([indextime, tp])

              if (indextime > data.max) {
                data.max = indextime
                if (data.min == 0) {
                  data.min = indextime
                }
              }
              if (indextime < data.min) {
                data.min = indextime
              }
            } catch {}
          }
      } catch {}
      yield put({
        type: 'updateState',
        payload: { realtime: data },
      })
    },
    *updaterealtimedata({ payload }, { call, put, select }) {
      yield put({
        type: 'updateState',
        payload: { realtime: payload },
      })
    },
    *exportExcel({ payload }, { call, put, select }) {
      const { Imei, startdate, enddate } = payload
      var sessionToken = sessionStorage.getItem('mr-ly-sessionToken-session')
      if (!sessionToken) {
        sessionToken = store.get('mr-ly-sessionToken')
      }
      var url = `http://langyuenbiot.leanapp.cn/exportExcel?Imei=${Imei}&startdate=${startdate}&enddate=${enddate}&session=${sessionToken}`
      var win = window.open(url, '_blank')
      // console.log(url)
      win.focus()
    },
    *refreshdataform({ payload }, { call, put, select }) {
      let { dtfstartdate, dtfenddate } = payload
      let startdate, enddate
      if (!dtfstartdate || !dtfenddate) {
        enddate = moment().format('YYYY-MM-DD')
        startdate = moment()
          .subtract(1, 'year')
          .format('YYYY-MM-DD')
      } else {
        enddate = dtfenddate
        startdate = dtfstartdate
      }

      const { result } = yield call(getUploadDatasList, {
        ...payload,
        startdate,
        enddate,
      })
      yield put({
        type: 'updateState',
        payload: {
          dataform: result,
          dtfstartdate: startdate,
          dtfenddate: enddate,
        },
      })
    },
    *getresolveddata({ payload }, { call, put, select }) {
      let { resstartdate, resenddate } = payload
      let startdate, enddate
      if (!resstartdate || !resenddate) {
        enddate = moment().format('YYYY-MM-DD')
        startdate = moment()
          .subtract(1, 'year')
          .format('YYYY-MM-DD')
      } else {
        enddate = resenddate
        startdate = resstartdate
      }
      const { result } = yield call(getresolvedhistorydata, {
        ...payload,
        startdate,
        enddate,
      })
      let data = {
        vmax: [],
        vmin: [],
        emax: [],
        emin: [],
        pmax: [],
        pmin: [],
        pv_vmax: [],
        pv_vmin: [],
        led_vmax: [],
        led_vmin: [],
        tpmax: [],
        tpmin: [],
        max: 0,
        min: 0,
      }
      for (let index in result) {
        let item = result[index]
        if (!item) continue
        const { Data, TimeToken } = item
        if (!Data) continue
        const {
          Emax,
          Emin,
          Pmax,
          Pmin,
          Vmax,
          Vmin,
          PV_Vmax,
          PV_Vmin,
          LED_Vmax,
          LED_Vmin,
          TPmax,
          TPmin,
        } = Data
        data.vmax.push([TimeToken, Vmax])
        data.vmin.push([TimeToken, Vmin])
        data.emax.push([TimeToken, Emax])
        data.emin.push([TimeToken, Emin])
        data.pmax.push([TimeToken, Pmax])
        data.pmin.push([TimeToken, Pmin])
        data.pv_vmax.push([TimeToken, PV_Vmax])
        data.pv_vmin.push([TimeToken, PV_Vmin])
        data.led_vmax.push([TimeToken, LED_Vmax])
        data.led_vmin.push([TimeToken, LED_Vmin])
        data.tpmax.push([TimeToken, TPmax])
        data.tpmin.push([TimeToken, TPmin])

        if (TimeToken > data.max) {
          data.max = TimeToken
          if (data.min == 0) {
            data.min = TimeToken
          }
        }
        if (TimeToken < data.min) {
          data.min = TimeToken
        }
      }
      yield put({
        type: 'updateState',
        payload: {
          rslaterdata: data,
          resstartdate: startdate,
          resenddate: enddate,
        },
      })
    },

    *onReceiveReport({ payload }, { call, put, select }) {
      const { onReceiveReport } = yield select(_ => _.userDetail)
      if (onReceiveReport) {
        // console.log("onReceiveReport is not null");
        onReceiveReport(payload)
      }
    },
    *subUpload({ payload }, { call, put, select }) {
      yield call(subUpload, payload)
      yield put({ type: 'updateState', payload: { SubReport: true } })
    },
    *unsubUpload({ payload }, { call, put, select }) {
      yield call(unsubUpload, payload)
    },
    *getAllDeviceGeo({ payload }, { call, put, select }) {
      const { result } = yield call(getAllDeviceGeo, payload)
      yield put({
        type: 'updateState',
        payload: {
          AllChildGeo: result,
        },
      })
    },
  },

  reducers: {
    querySuccess(state, { payload }) {
      const { data, deviceid, pathquery } = payload
      return {
        ...state,
        ...(data ? { data } : {}),
        ...(deviceid ? { deviceid } : {}),
        ...(pathquery ? { pathquery } : {}),
      }
    },
    back(state, { payload }) {
      // const { data, deviceid, pathquery } = payload
      return {
        ...emptystate,
      }
    },
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
  },
}
